<template>
  <div>
    <el-card class="box-card">
      <el-tabs :tab-position="tabPosition">
        <el-tab-pane label="登录时间">
          <el-divider><i class="el-icon-caret-left"></i></el-divider>
          <el-card class="box-card">
            <el-timeline>
              <el-timeline-item v-for="item in lists" :key="item.id" :timestamp="item.loginDate" placement="top">
                <p><i class="el-icon-link"></i> IP： {{ item.requestIp }}</p>
                <p><i class="el-icon-location-outline"></i> 地区：{{ item.location }}</p>
                <p><i class="el-icon-bangzhu"></i> 浏览器：{{ item.browser }}</p>
                <p><i class="el-icon-monitor"></i> 操作系统：{{ item.operatingSystem }}</p>
              </el-timeline-item>
            </el-timeline>
          </el-card>
        </el-tab-pane>
        <el-tab-pane label="账号信息">
          <el-divider><i class="el-icon-caret-left"></i></el-divider>
          <el-card class="box-card">
            <el-form :rules="userrules" :model="user" :ref="user" label-position="right" label-width="100px">
              <el-form-item label="系统头像：">
                <div class="logoBox">
                  <div class="changeLogo">
                    <el-upload
                      action="/OSSFileApi/file/upload"
                      :show-file-list="false"
                      :on-success="handleAvatarSuccess"
                      :before-upload="beforeAvatarUpload">
                      <img v-if="user.avatar" :src="this.ossaddr+'/'+user.avatar" alt class="changeLogo"/>
                      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                  </div>
                  <!--                  <div id="qrcode"></div>-->
                </div>
              </el-form-item>
              <el-form-item label="姓名：" prop="name">
                <el-input v-model="user.name"></el-input>
              </el-form-item>
              <el-form-item label="邮箱：" prop="email">
                <el-input v-model="user.email"></el-input>
              </el-form-item>
              <el-form-item label="电话：" prop="mobile">
                <el-input v-model="user.mobile"></el-input>
              </el-form-item>
              <el-form-item label="性别：" prop="sex">
                <el-select style="width:100%" v-model="user.sex">
                  <el-option label="未知" value="N"></el-option>
                  <el-option label="女" value="W"></el-option>
                  <el-option label="男" value="M"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="个人描述：">
                <el-input type="textarea" v-model="user.workDescribe"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button @click="update">修改</el-button>
                <el-button type="primary" @click="createQrCodeInfo">生成个人信息二维码</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </el-tab-pane>
        <el-tab-pane label="个人密码">
          <el-divider><i class="el-icon-caret-left"></i></el-divider>
          <el-card class="box-card">
            <el-form :rules="passwordrules" :model="password" :ref="password" :inline="true" label-width="200px">
              <el-form-item label="旧密码：" prop="oldPwd">
                <el-input style="width: 370px" v-model="password.oldPwd" type="password"></el-input>
              </el-form-item>
              <el-form-item label="新密码：" prop="newPwd">
                <el-input style="width: 370px" v-model="password.newPwd" type="password"></el-input>
              </el-form-item>
              <el-form-item label="确认密码：" prop="againPwd">
                <el-input style="width: 370px" v-model="password.againPwd" type="password"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button @click="updatePassword">修改</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <el-dialog
      title="用户名片"
      :visible.sync="dialogVisible"
      width="22.4%">
      <div id="qrcode"></div>
    </el-dialog>
  </div>
</template>
<script>
import myCenterAPI from "../api/basicfunction/basicmenu/myCenterAPI";
import {mapState} from 'vuex'

export default {
  name: "myCenter",
  computed: {
    ...mapState(['ossaddr'])
  },
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        if (this.password.againPwd !== '') {
          this.$refs.password.validateField('againPwd');
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.password.newPwd) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      picture: "",
      tabPosition: 'left',
      lists: [],
      user: {},
      password: {},
      userrules: {
        mobile: [{
          pattern: /^(13[0-9]|14[5-9]|15[012356789]|166|17[0-8]|18[0-9]|19[8-9])[0-9]{8}$/,
          message: "手机号格式不对",
          trigger: "blur"
        }],
        email: [{type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change']}],
        sex: [{required: true, message: '请选择性别', trigger: 'change'}]
      },
      passwordrules: {
        oldPwd: [{required: true, message: '不能为空', trigger: 'blur'}],
        newPwd: [
          {required: true, message: '不能为空', trigger: 'blur'},
          {min: 6, max: 20, message: '长度在6-20个字符之间', trigger: 'blur'},
          {validator: validatePass, trigger: 'blur'}
        ],
        againPwd: [
          {required: true, message: '不能为空', trigger: 'blur'},
          {validator: validatePass2, trigger: 'blur', required: true}
        ],
      },
      dialogVisible: false
    }
  },
  methods: {
    list() {
      myCenterAPI.selLogAll().then(({data}) => {
        this.lists = data.data
      })
    },
    createQrCodeInfo() {
      this.dialogVisible = !this.dialogVisible
      setTimeout(() => {
        document.getElementById('qrcode').innerHTML = ''
        //获取值
        var headImg = "PHOTO;VALUE=uri:" + this.ossaddr + '/' + this.user.avatar + "\n";
        var name = "FN:" + this.user.name + "\n";
        var company = "ORG:" + this.user.orgName + "\n";
        var job = "TITLE: " + "品达工作人员\n";
        var moblie = "TEL:" + this.user.mobile + "\n";
        var email = "EMAIL:" + this.user.email + "\n";
        var desc = "NOTE:" + this.user.workDescribe + "\n";
        var info = "BEGIN:VCARD\n" + headImg + name + company + job + moblie + email + desc + "END:VCARD";
        var qrcode = new QRCode("qrcode", {
          width: 300,
          height: 300,
          correctLevel: 2,
        })
        qrcode.makeCode(info);
      }, 400)
    },
    getUser() {
      myCenterAPI.getUser().then(({data}) => {
        this.user = data.data
      })
    },
    update() {
      this.$store.commit("startAnimation", true);
      myCenterAPI.updateUser(this.user).then(({data}) => {
        this.$store.commit("startAnimation", false);
        if (data.code === 200) {
          this.$root.Bus.$emit('userUpdate', true) // 发送一个通知给头刷新信息
          this.$message({
            message: data.message,
            type: 'success'
          });
        } else {
          this.$message.error(data.message);
        }
      })
    },
    updatePassword() {
      this.$store.commit("startAnimation", true);
      if (this.password) {
        myCenterAPI.updatePassword(this.password).then(({data}) => {
          this.$store.commit("startAnimation", false);
          if (data.code === 200) {
            this.$message({
              message: data.message,
              type: 'success'
            });
            this.$store.commit('logout', null)
            this.$router.push('/login')
          } else {
            this.$message.error(data.message);
          }
        })
      }
    },
    // 上传成功后
    handleAvatarSuccess(res, file) {
      if (res.code === 200) {
        this.$store.commit("startAnimation", false);
        this.user.avatar = res.data.url
      }
    },
    // 上传之前
    beforeAvatarUpload(file) {
      this.$store.commit("startAnimation", true);
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$store.commit("startAnimation", false);
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$store.commit("startAnimation", false);
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    }
  },
  created() {
    this.list();
    this.getUser();
  }
}
</script>
<style scoped>
el-form-item {
  width: 100%;
  display: block;
}

.logoBox {
  width: 100%;
  height: 100px;
  text-align: center;
  display: flex;
}

.changeLogo {
  margin: auto;
  height: 100px;
  width: 100px;
  border-radius: 60px;
  text-align: center;
  cursor: pointer;
}
</style>
